﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WebCycle
{
    public partial class Settings : Form
    {
        private ScreensaverConfiguration _config = new ScreensaverConfiguration();

        public Settings()
        {
            InitializeComponent();
            urls.Text = string.Join("\r\n", _config.Urls.ToArray());
            delay.Text = (_config.Delay / 1000.0).ToString();
        }
        private void OkButton_Click(object sender, System.EventArgs e)
        {
            if (Save())
            {
                Close();
            }
        }

        private bool Save()
        {
            try
            {
                int.Parse(delay.Text);
            }
            catch
            {
                MessageBox.Show("Invalid delay time, default value was set", "Invalid delay time");
                delay.Text = _config.Delay.ToString();
            }

            if (string.IsNullOrEmpty(urls.Text.Trim()))
            {
                urls.Text = string.Join(",", _config.Urls.ToArray());
            }

            foreach (string url in urls.Text.Trim().Replace("\r\n", ",").Split(','))
            {
                if(!string.IsNullOrEmpty(url.Trim()))
                {
                    try
                    {
                        Uri test = new Uri(url);
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(url + " is not a valid URL","Invalid URL");
                        return false;
                    }
                }
            }
            _config.SaveConfigToRegistry(urls.Text.Trim().Replace("\r\n", ","), int.Parse(delay.Text));
            return true;
        }

        private void cancelButton_Click(object sender, System.EventArgs e)
        {
            Close();
        }
    }
}
